package com.insight.common.filter.emoji;

import com.alibaba.fastjson.JSON;
import com.yuanqiao.insight.common.util.common.EmojiFilterUtil;
import com.insight.common.api.vo.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
@WebFilter(urlPatterns = "/*")
public class EmojiFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String contentType = httpRequest.getContentType();

        // 处理 application/json 请求
        if (contentType != null && contentType.equals("application/json")) {
            CachedBodyHttpServletRequestWrapper wrappedRequest = new CachedBodyHttpServletRequestWrapper(httpRequest);
            String requestBody = wrappedRequest.getBody();

            // 检查是否包含 emoji
            if (EmojiFilterUtil.containsEmoji(requestBody)) {
                sendErrorResponse(httpResponse);
                return;
            }

            //String a = wrappedRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator()));

            // 继续处理请求
            chain.doFilter(wrappedRequest, response);
        }  else {
            // 其他类型的请求，检查表单和文件名
            if (containsEmojiInFormRequest(httpRequest)) {
                sendErrorResponse(httpResponse);
                return;
            }
            chain.doFilter(request, response);
        }
    }

    // 检查表单请求中的文本和文件名是否包含 emoji
    private boolean containsEmojiInFormRequest(HttpServletRequest request) {
        // 检查表单字段
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String[] values = entry.getValue();
            for (String value : values) {
                if (EmojiFilterUtil.containsEmoji(value)) {
                    return true;
                }
            }
        }

        // 检查 multipart 请求中的文件名
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            for (MultipartFile file : fileMap.values()) {
                String originalFilename = file.getOriginalFilename();
                if (EmojiFilterUtil.containsEmoji(originalFilename)) {
                    return true;
                }
            }
        }

        return false;
    }

    // 返回错误响应
    private void sendErrorResponse(HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentType("application/json; charset=UTF-8");
        Result<Object> result = Result.OK().error500("请求参数中包含非法字符");
        response.getWriter().write(JSON.toJSONString(result));
    }

    // 统一处理 form-data 和 x-www-form-urlencoded 的请求
    private void filterFormRequest(HttpServletRequest request) throws IOException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String[] values = entry.getValue();
            for (int i = 0; i < values.length; i++) {
                // 过滤掉参数值中的 emoji 表情
                values[i] = EmojiFilterUtil.removeEmoji(values[i]);
            }
        }
    }

}
